<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\exception\ValidateException;
use app\addons\File;
use app\admin\BaseController;
use app\admin\model\Config;
use app\admin\model\Catalog;
use app\admin\model\Themes as ThemesModel;
use app\admin\validate\Themes as ThemesValidate;
/**
 * 主题管理
 */
class Themes extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input   = input();
            $install = ThemesModel::select();
            if ($input['install'] == 1) {
                // 已安装
                $list  = $install;
                $count = 0;
                foreach ($install as $key => $val) {
                    $list[$key]['status'] = "1";
                    $list[$key]['cover']  = config('app.api').$val['cover'];
                }
            } else {
                // 主题中心
                $res   = api_post('themes/getList', $input);
                $list  = [];
                $count = 0;
                if ($res['status'] === 'success') {
                    $list  = $res['data'];
                    $count = $res['count'];
                    foreach ($list as $key => $val) {
                        $list[$key]['status'] = "0";
                        $list[$key]['cover']  = config('app.api').$val['cover'];
                        foreach ($install as $k => $v) {
                            if ($val['name'] === $v['name']) {
                                $list[$key]['status'] = "1";
                            }
                        }
                    }
                }
            }
            return json(['status' => 'success', 'data' => $list, 'count' => $count]);
        } else {
            // 主题分类
            $catalog = cache('themesCatalogList');
            if (empty($catalog)) {
                $res = api_post('themes/getCatalogList');
                $catalog = $res['status'] === 'success' ? $res['data'] : [];
                cache('themesCatalogList', $catalog);
            }
            // 启动主题
            $theme['pc_template'] = config('app.pc_template');
            $theme['mp_template'] = config('app.mp_template');
            View::assign([
                'catalog' => $catalog,
                'theme'   => $theme,
            ]);
        }
        return View::fetch();
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(ThemesValidate::class)->scene('delete')->check($input);
            $template = [config('app.pc_template'),config('app.mp_template')];
            if (! in_array($input['name'], $template)) {
                $path = theme_path() . $input['name'];
                // 删除文件
                File::delDirAndFile($path);
                // 修改数据
                Db::startTrans();
                try {
                    // 列表
                    ThemesModel::where('name', $input['name'])->delete();
                    // 配置
                    Config::whereLike('name','%theme_'.$input['name'].'_%')->delete();
                    // 提交更改
                    Db::commit();
                    return json(['status' => 'success', 'message' => '卸载成功']);
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['status' => 'error', 'message' => '卸载失败']);
                }
            } else {
                return json(['status' => 'error', 'message' => '主题启用中，不能卸载']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 创建订单
     */
    public function createOrder()
    {
        if ($this->request->isPost()) {
            $input = input();
            $res   = api_post('themes/createOrder', $input);
            return json($res);
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(ThemesValidate::class)->scene('update')->check($input);
            $pat[] = 'pc_template';
            $pat[] = 'mp_template';
            $rep[] = $input['pc_template'];
            $rep[] = $input['mp_template'];
            File::editConfig($pat, $rep, config_path().'app.php');
            return json(['status' => 'success', 'message' => '主题切换成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
    /**
     * 安装包初始化
     */
    public function init($input, $res)
    {
        $path = theme_path() . $input['name'] . '/';
        if (! is_dir($path)) {
            // 基本信息
            $info = $res['data']['info'];
            // 创建文件
            File::create($path.'file.zip', base64_decode($res['data']['zip']));
            // 执行解压
            File::extract($path.'file.zip', $path);
            // 覆盖资源
            File::dirCopy($path . 'upload', public_path() . "upload/themes/" . $input['name']);
            // 删除缓存
            $cacheName = 'catalog_'.$this->request->langDefault;
            cache($cacheName, NULL);
            Db::startTrans();
            try {
                // 创建主题
                ThemesModel::create([
                    'name'   => $info['name'],
                    'title'  => $info['title'],
                    'cover'  => $info['cover'],
                    'price'  => $info['price'],
                    'type'   => $info['type'],
                    'config' => $info['config'],
                ]);
                // 覆盖分类
                $catalog = Catalog::where('language',$this->request->langDefault)->column('seo_url');
                foreach ($res['data']['catalog'] as $index => $item) {
                    if (! in_array($item['seo_url'], $catalog)) {
                        unset($item['theme'],$item['id']);
                        Catalog::create($item);
                    }
                }
                // 生成配置
                foreach ($this->request->langAllow as $key => $lang) {
                    $name  = 'theme_' . $info['name'] . '_' . $lang['name'];
                    $title = $info['title'].'主题配置';
                    $value = json_encode($info['config']);
                    Config::setVal($name, $title, $value);
                }
                Db::commit();
                return ['status' => 'success', 'message' => '安装成功'];
            } catch (\Exception $e) {
                Db::rollback();
                return ['status' => 'error', 'message' => '安装失败'];
            }
        } else {
            return ['status' => 'error', 'message' => '主题已存在'];
        }
    }
    /**
     * 上传插件包
     */
    public function upload() 
    {
        if (! is_dir(theme_path())) {
            mkdir(theme_path(), 0777, true);
        }
        if (is_writable(theme_path())) {
            $input = input();
            $arr   = explode('.', $_FILES['file']['name']);
            $input['name'] = $arr[0];
            $res = api_post('themes/orderFile', $input);
            if ($res['status'] === 'success') {
                $res = $this->init($input, $res);
                return json($res);
            } else {
                return json($res);
            }
        } else {
            return json(['status' => 'error', 'message' => '插件目录没有写入权限']);
        }
    }

    /**
     * 安装主题
     */
    public function install()
    {
        if (! is_dir(theme_path())) {
            mkdir(theme_path(), 0777, true);
        }
        if (is_writable(theme_path())) {
            try {
                $input = input();
                validate(ThemesValidate::class)->scene('install')->check($input);
                $data['id'] = $input['id'];
                $res = api_post('themes/getFile', $data);
                if ($res['status'] === 'success') {
                    $init = $this->init($input, $res);
                    if ($init) {
                        return json(['status' => 'success', 'message' => '安装成功']);
                    } else {
                        return json(['status' => 'error', 'message' => '安装失败']);
                    }
                } else {
                    return json($res);
                }
            } catch ( ValidateException $e ) {
                return json($e->getError());
            }
        } else {
            return json(['status' => 'error', 'message' => '主题目录没有写入权限']);
        }
    }

    /**
     * 主题配置
     */
    public function config()
    {
        try {
            $input = input();
            validate(ThemesValidate::class)->scene('config')->check($input);
            $name  = 'theme_' . $input['name'] . '_' . $this->request->lang;
            $data  = ThemesModel::field('config, title')->where('name', $input['name'])->find();
            if ($data) {
                $data = $data->toArray();
                $value = Config::getVal($name);
                foreach ($data['config'] as $key => $val) {
                    $data['config'][$key]['value'] = isset($value[$val['field']]) ? $value[$val['field']] : $val['value'];
                }
                return json(['status' => 'success', 'message' => '获取成功', 'data' => $data]);
            } else {
                return json(['status' => 'error', 'message' => '获取失败']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 更改主题配置
     */
    public function configUpdate()
    {
        try {
            $input = input();
            validate(ThemesValidate::class)->scene('configUpdate')->check($input);
            $name   = 'theme_' . $input['name'] . '_' . $this->request->lang;
            $themes = ThemesModel::field('config, title')->where('name', $input['name'])->find();
            $title  = $themes['title'].'主题配置';
            $config = $input['config'];
            $value  = [];
            foreach ($config as $key => $val) {
                $value[$val['field']]  = $val['value'];
            }
            Config::setVal($name, $title, $value);
            $themes->config = $config;
            $themes->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}
